package com.codeberry.yws;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContextMap {
  private ContextHandler defaultHandler;
  private Map<String, ContextHandler> handlers = new ConcurrentHashMap<String,ContextHandler>();

  public ContextMap(ContextHandler defaultHandler) {
    this.defaultHandler = defaultHandler;
  }

  public ContextHandler get(String fullPath) {
    fullPath = trimSlash(fullPath);
    String[] parts = fullPath.split("/");
    String lookupPath = "";

    for (String part : parts) {
      lookupPath += part;
      
      ContextHandler foundHandler = handlers.get(lookupPath);
      if (foundHandler != null) {
        return foundHandler;
      }

      lookupPath += "/";
    }

    return defaultHandler;
  }

  public void put(String path, ContextHandler handler) {
    path = trimSlash(path);
    handlers.put(path, handler);
  }

  private String trimSlash(String str) {
    while (!str.isEmpty() &&
           str.charAt(0) == '/') {
      str = str.substring(1);
    }
    while (!str.isEmpty() &&
           str.charAt(str.length() - 1) == '/') {
      str = str.substring(0, str.length() - 1);
    }
    return str;
  }
}
